package com.springboot.rookie.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.rookie.controller.system.SysMenuController;
import com.springboot.rookie.pojo.SysMenuBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HomeController {

    @Autowired
    CommonController commonController;
    @Autowired
    SysMenuController sysMenuController;

    private ObjectMapper objectMapper;
    private static final String TEMPLATE_PATH = "component/";

    @RequestMapping("/main")
    public String home(@RequestParam(value = "language", required = false, defaultValue = "zh_CN") String language,
                       @RequestParam(value = "menu", required = false, defaultValue = "WaterConservancy") String menu,
                       @RequestParam(value = "fragment", required = false, defaultValue = "Analytics") String fragment,
                       Model model,
                       HttpSession session) throws JsonProcessingException {
        //获取菜单
        List<SysMenuBean> menuList = sysMenuController.getAll();
        //将菜单列表保存到session中
        objectMapper = new ObjectMapper();
        session.setAttribute("menuList", objectMapper.writeValueAsString(menuList));
        //将多语言保存到session中
        session.setAttribute("language", language);

        initModel(language, model, menuList, menu, fragment);
        return "home";
    }

    @RequestMapping("/menu")
    public String menu(@RequestParam("menu") String menu,
                       @RequestParam("fragment") String fragment,
                       @RequestParam(value = "id", required = false, defaultValue = "0") Integer id,
                       Model model, HttpSession session) throws JsonProcessingException {

        String menuJson = (String) session.getAttribute("menuList");
        List<SysMenuBean> menuList = objectMapper.readValue(menuJson, objectMapper.getTypeFactory().constructCollectionType(List.class, SysMenuBean.class));

        String language = (String) session.getAttribute("language");
        initModel(language, model, menuList, menu, fragment);

        if ("MenuAdd".equals(fragment)) {
            //菜单选项列表
            List<SysMenuBean> menuOptionList = new ArrayList<>();
            for (SysMenuBean info : menuList) {
                menuOptionList.add(info);
                if (info.getChildList() != null) {
                    menuOptionList.addAll(info.getChildList());
                }
            }
            model.addAttribute("menuOptionList", menuOptionList);
            if (id != 0) {
                SysMenuBean menuBean = sysMenuController.getById(id);
                model.addAttribute("menuBean", menuBean);
            }
        }
        return "home";
    }

    @PostMapping("/menuSaveOrUpdate")
    public String menuSaveOrUpdate(SysMenuBean info) {
        boolean result = sysMenuController.saveOrUpdate(info);
        String route = result ? "main" : "menu";
        String fragment = result ? "MenuManage" : "MenuAdd";
        return "redirect:/" + route + "?menu=SysManage&fragment=" + fragment;
    }

    @RequestMapping("/menuEdit")
    public String menuEdit(@RequestParam("id") Integer id) {
        return "redirect:/menu?menu=SysManage&fragment=MenuAdd&id=" + id;
    }

    @RequestMapping("/menuDel")
    public String menuDel(@RequestParam("id") Integer id) {
        boolean result = sysMenuController.deleteSingle(id);
        String route = result ? "main" : "menu";
        return "redirect:/" + route + "?menu=SysManage&fragment=MenuManage";
    }

    /**
     * 设置Model
     * @param model
     * @param menuList 菜单列表
     * @param menuActive 选中的菜单
     * @param fragment 模板片段
     */
    private void initModel(String language, Model model, List<SysMenuBean> menuList, String menuActive, String fragment) {
        //多语言
        model.addAttribute("languageList", commonController.getLanguageList(language));
        //消息
        model.addAttribute("messageList", commonController.getMessageList(1));
        //通知
        model.addAttribute("notifyList", commonController.getNotifyList(1));


        String rootName = "";
        String secondName = "";
        String currentName = "";

        if (menuList != null && menuList.size() > 0) {
            //根导航
            for (SysMenuBean item : menuList) {
                if (item.getChildList() != null) {
                    //二级导航
                    for (SysMenuBean childItem : item.getChildList()) {
                        if (StringUtils.isEmpty(menuActive)) {
                            rootName = item.getName();
                            secondName = childItem.getName();
                        } else {
                            if (childItem.getMenuMarks().equals(menuActive)) {
                                rootName = item.getName();
                                secondName = childItem.getName();
                            }
                        }

                        if (!StringUtils.isEmpty(secondName) && childItem.getChildList() != null) {
                            //三级导航
                            for (SysMenuBean currentItem : childItem.getChildList()) {
                                if (StringUtils.isEmpty(menuActive)) {
                                    currentName = currentItem.getName();
                                    break;
                                } else {
                                    if (currentItem.getMenuMarks().equals(fragment)) {
                                        currentName = currentItem.getName();
                                        break;
                                    }
                                }
                            }
                            break;
                        }

                        if (StringUtils.isEmpty(menuActive)) {
                            break;
                        }
                    }

                    if (!StringUtils.isEmpty(rootName)) {
                        break;
                    }
                } else {
                    if (item.getMenuMarks().equals(menuActive)) {
                        rootName = item.getName();
                        break;
                    }
                }
            }
        }

        //菜单列表
        model.addAttribute("menuList", menuList);
        //选中的菜单
        model.addAttribute("menuActive", menuActive);
        //模版路径
        model.addAttribute("templatePath", TEMPLATE_PATH + StringUtils.uncapitalize(fragment));
        //选中的fragment（模板片段）
        model.addAttribute("fragment", fragment);
        model.addAttribute("rootName", rootName);
        model.addAttribute("secondName", secondName);
        model.addAttribute("currentName", currentName);
    }
}
